package com.rf.richfitwheel.admin.sys.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.rf.richfitwheel.admin.annotation.NoRepeatSubmit;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.sys.model.Menu;
import com.rf.richfitwheel.admin.sys.model.MenuBean;
import com.rf.richfitwheel.admin.sys.model.User;
import com.rf.richfitwheel.admin.sys.service.SysMenuService;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL+"/menu")
public class SysMenuController {

	private static Logger log = LoggerFactory.getLogger(SysMenuController.class);
	
	@Autowired
	private SysMenuService sysMenuService;
	
	/**
	 * 列表查询
	 * @param params
	 * @return
	 */
	@GetMapping("/list")
//	@RequiresPermissions("sys:menu:list")
	public List<Menu> list(@RequestParam Map<String, Object> params){
		JSONObject obj = StringUtils.isBlank(params.get("dataForm")) ? null : JSONObject.fromObject(params.get("dataForm"));
		List<Menu> menuList = sysMenuService.selectList(obj);
		return menuList;//menuList;
	}
	
	/**
	 * 记录用户菜单点击行为
	 * @param menuId
	 * @return
	 */
	@GetMapping("/menuClick/{menuId}")
//	@UserOperateLog(module="系统功能",methods="menuClick",description="菜单点击")
	public R menuClick(@PathVariable("menuId") String menuId) {
		UserVO userVO = UserUtil.getUser();
		try {
			sysMenuService.menuClick(menuId, userVO);
		} catch (Exception e) {
			log.error("记录用户菜单点击失败", e);
		}
		return R.ok();
	}
	
	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@GetMapping("/select")
//	@RequiresPermissions("sys:menu:select")
	public R select(){
		//查询列表数据
		List<MenuBean> menuList = sysMenuService.queryNotButtonList();
		
		//添加顶级菜单
		MenuBean root = new MenuBean();
		root.setId("0");
		root.setName("菜单");
		root.setParentId("-1");
		root.setOpen(true);
		menuList.add(root);
		
		return R.ok().put("menuList", menuList);
	}

	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@GetMapping("/selectByModule/{moduleType}")
//	@RequiresPermissions("sys:menu:select")
	public R select(@PathVariable("moduleType") String moduleType){
		//查询列表数据
		List<MenuBean> menuList = sysMenuService.queryByModuleNotButtonList(moduleType);

		//添加顶级菜单
		MenuBean root = new MenuBean();
		root.setId("0");
		root.setName("菜单");
		root.setParentId("-1");
		root.setOpen(true);
		menuList.add(root);

		return R.ok().put("menuList", menuList);
	}


	/**
	 * 菜单信息
	 */
	@GetMapping("/info/{menuId}")
//	@RequiresPermissions("sys:menu:info")
	public R info(@PathVariable("menuId") String menuId){
		Menu menu = sysMenuService.selectById(menuId);
		return R.ok().put("menu", menu);
	}
	/**
	 * 菜单信息
	 */
	@GetMapping("/infoAndParentInfo/{menuId}")
//	@RequiresPermissions("sys:menu:info")
	public R infoAndParentInfo(@PathVariable("menuId") String menuId){
		Menu menu = sysMenuService.selectById(menuId);
		Menu pmenu = sysMenuService.selectById(menu.getParentId());
		return R.ok().put("menu", menu).put("pmenu",pmenu);
	}
	/**
	 * 新增菜单
	 * @param menu
	 * @return
	 */
	@UserOperateLog(module="系统功能",methods="save",description="新增资源")
	@PostMapping("/save")
	@NoRepeatSubmit
//	@RequiresPermissions("sys:menu:save")
	public R save(@RequestBody Menu menu){
		try {
			//数据校验
			verifyForm(menu);
			UserVO userVO = UserUtil.getUser();
			Date date = new Date();
			menu.setCreater(userVO.getId());
			menu.setCreateTime(date);
			menu.setModUser(userVO.getId());
			menu.setModTime(date);
			String tenantId = "";
			if(userVO.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
				tenantId = menu.getTenantId();
			} else {
				tenantId = userVO.getTenantId();
			}
			menu.setTenantId(tenantId);
			sysMenuService.insert(menu);
			
			return R.ok();
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.error("系统错误");
		}
	}
	
	/**
	 * 修改
	 */
	@UserOperateLog(module="系统功能",methods="update",description="更新资源")
	@PostMapping("/update")
//	@RequiresPermissions("sys:menu:update")
	public R update(@RequestBody Menu menu){
		try {
			//数据校验
			verifyForm(menu);
					
			sysMenuService.updateById(menu);
			
			return R.ok();
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.error("系统错误");
		}
	}
	
	/**
	 * 删除
	 */
	@UserOperateLog(module="系统功能",methods="delete",description="删除资源")
	@PostMapping("/delete/{id}")
//	@RequiresPermissions("sys:menu:delete")
	public R delete(@PathVariable("id") String id){
		if("1".equals(id) || "2".equals(id) || "3".equals(id) || "4".equals(id)) {
			return R.error("系统基础资源，不能删除");
		}

		//判断是否有子菜单或按钮
		List<MenuBean> menuList = sysMenuService.queryListParentId(id);
		if(menuList.size() > 0){
			return R.error("请先删除子菜单或按钮");
		}

		sysMenuService.delete(id);

		return R.ok();
	}
	
	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(Menu menu){
		if(StringUtils.isBlank(menu.getName())){
			throw new BusinessException("菜单名称不能为空");
		}
		
		if(menu.getParentId() == null){
			throw new BusinessException("上级菜单不能为空");
		}
		
		//菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()){
			if(StringUtils.isBlank(menu.getUrl())){
				throw new BusinessException("菜单URL不能为空");
			}
		}
		
		//上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if(menu.getParentId() != "0"){
//			Menu parentMenu = sysMenuService.selectById(menu.getParentId());
//			parentType = parentMenu.getType();
		}
		
		//目录、菜单
		if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
				menu.getType() == Constant.MenuType.MENU.getValue()){
			if(parentType != Constant.MenuType.CATALOG.getValue()){
//				throw new BusinessException("上级菜单只能为目录类型");
			}
			return ;
		}
		
		//按钮
		if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
			if(parentType != Constant.MenuType.MENU.getValue()){
//				throw new BusinessException("上级菜单只能为菜单类型");
			}
			return ;
		}
	}

	
}
